package com.ishanshan.gateway.aop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by WANGHJ on 2019-04-26.
 */
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/api/*",filterName = "requestFiflter")
public class RequestFiflter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger("requestInfo");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Long startTime = System.currentTimeMillis();
        filterChain.doFilter(servletRequest,servletResponse);
        Long endTime = System.currentTimeMillis();
        Long time = endTime - startTime;
        if(time>2000){
            if(servletRequest instanceof HttpServletRequest){
                logger.error("请求路径为;【{}】,耗时:【{}】ms",((HttpServletRequest) servletRequest).getRequestURI(),time);
            }

        }
    }

    @Override
    public void destroy() {

    }
}